package com.ikangtai.shecare.personal;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.ikangtai.shecare.common.util.Validator;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;

public class AboutFeedbackActivity extends BaseActivity implements View.OnClickListener {

    private TopBar topBar;
    private EditText name_edit, email_edit, phone_edit, content_edit;
    private Validator Validator = new Validator();
    private static final int FEEDBACK_OK = 1;
    private static final int FEEDBACK_NOK = 2;
    private String userName;
    private String userEmail;
    private String userPhone;
    private String userContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_personal_about_feedback);
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        topBar = (TopBar) findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void midLeftClick() {

            }

            @Override
            public void midRightClick() {

            }

            @Override
            public void rightClick() {

            }
        });
        name_edit = (EditText) findViewById(R.id.name_edit);
        email_edit = (EditText) findViewById(R.id.email_edit);
        phone_edit = (EditText) findViewById(R.id.phone_edit);
        content_edit = (EditText) findViewById(R.id.content_edit);
        findViewById(R.id.feedback_btn).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.feedback_btn:

                if (isValid()) {
                    sendFeedback(userEmail, userPhone, userContent);
                } else {

                }

                break;
        }
    }

    /**
     * 检查文本框内容
     */
    private boolean isValid() {
        userName = name_edit.getText().toString().trim();
        userEmail = email_edit.getText().toString().trim();
        userPhone = phone_edit.getText().toString().trim();
        userContent = content_edit.getText().toString().trim();

        if (0 == userEmail.length()) {
            Toast.makeText(getApplicationContext(), R.string.mailbox_not_null, Toast.LENGTH_SHORT).show();
        } else if (!Validator.isEmail(userEmail)) {
            Toast.makeText(getApplicationContext(), R.string.mailbox_not_true, Toast.LENGTH_SHORT).show();
        } else if (0 == userPhone.length()) {
            Toast.makeText(getApplicationContext(), R.string.phone_not_null, Toast.LENGTH_SHORT).show();
        } else if (!Validator.isMobile(userPhone)) {
            Toast.makeText(getApplicationContext(), R.string.phone_not_true, Toast.LENGTH_SHORT).show();
        } else if (0 == userContent.length()) {
            Toast.makeText(getApplicationContext(), R.string.context_not_null, Toast.LENGTH_SHORT).show();
        } else {
            return true;
        }
        return false;
    }

    /**
     * post请求
     *
     * @param userEmail
     * @param userPhone
     * @param userContent
     */
    private void sendFeedback(final String userEmail, final String userPhone, final String userContent) {
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "feed/feedback.json";
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("APPVersion", getVersion());
            okHttpClient.add("feedback", userContent);
            okHttpClient.add("contactWay", "Email：" + userEmail + "  Phone：" + userPhone);
            okHttpClient.add("OSType", "and");
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    sendNOKResp(FEEDBACK_NOK);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            sendOKResp(FEEDBACK_OK);
                            AppLog.i("feedback onResponse success!");
                            finish();
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            sendFeedback(userEmail, userPhone, userContent);
                        } else {
                            sendNOKResp(FEEDBACK_NOK);
                            AppLog.i("feedback onResponse respCode failed! is:" + respCode);
                        }
                    } catch (JSONException e) {
                        AppLog.i("feedback onResponse failed!");
                        sendNOKResp(FEEDBACK_NOK);
                        e.printStackTrace();
                    }
                }

            });
        } catch (JSONException e) {
            sendNOKResp(FEEDBACK_NOK);
            e.printStackTrace();
        }
    }

    private void sendNOKResp(int returnCode) {
        EventBus.getDefault().post(Integer.valueOf(returnCode));
    }

    private void sendOKResp(int returnCode) {
        EventBus.getDefault().post(Integer.valueOf(returnCode));
    }

    @Subcriber
    private void handleMyInfo(Integer returnCode) {
        switch (returnCode) {
            case FEEDBACK_OK:
                Toast.makeText(getApplicationContext(), R.string.send_success, Toast.LENGTH_SHORT).show();
                break;

            case FEEDBACK_NOK:
                //Toast.makeText(getApplicationContext(), "发送失败!", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public String getVersion() {
        AppLog.i("getVersion in AboutActivity!");
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = packInfo.versionName;
        return version;
    }
}
